<template>
  <div>
    <el-dialog title="选择素材"
               append-to-body
               :visible.sync="materialVisible"
               :before-close="handleClose"
               :close-on-click-modal="false"
               width="1080px">
      <el-row :gutter="30">
        <el-col :xl="6"
                :lg="6"
                :md="6"
                :sm="6"
                :xs="24">
          <div class="Nav">
            <div class="input">
              <el-input v-model="filterText"
                        placeholder="选择分类"
                        prefix-icon="el-icon-search"
                        style="width: 100%"
                        clearable />
            </div>
            <div class="trees-coadd">
              <div class="scollhide">
                <div class="trees">
                  <el-tree ref="tree"
                           :data="treeData"
                           :filter-node-method="filterNode"
                           :props="defaultProps"
                           highlight-current>
                    <div slot-scope="{ node, data }"
                         class="custom-tree-node"
                         @click.stop="handleNodeClick(data)">
                      <div>
                        <span class="custom-tree-node-label"
                              :title="node.label">{{ node.label }}</span>
                      </div>
                      <span class="el-ic"
                            v-if="permissions.sys_tree_all || permissions.material_add || permissions.material_edit || permissions.material_del">
                        <el-dropdown>
                          <span class="el-dropdown-link">
                            <i class="el-icon-more-outline"
                               style="color:red;"></i>
                          </span>
                          <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item v-if="permissions.sys_tree_all || permissions.material_add"
                                              @click.native="onAdd(data)">添加分类</el-dropdown-item>
                            <el-dropdown-item v-if="(permissions.sys_tree_all || permissions.material_edit) && data.id != 0"
                                              @click.native="onEdit(data.id)">编辑分类</el-dropdown-item>
                            <el-dropdown-item v-if="(permissions.sys_tree_all || permissions.material_del) && data.id != 0"
                                              @click.native="handleDelete(data.id)">删除分类</el-dropdown-item>
                          </el-dropdown-menu>
                        </el-dropdown>
                      </span>
                    </div>
                  </el-tree>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :xl="18"
                :lg="18"
                :md="18"
                :sm="18"
                :xs="24"
                class="colLeft">
          <div class="conter mb15 relative">
            <div class="bnt">
              <el-button size="small"
                         type="success"
                         class="mr15 mb20"
                         icon="el-icon-check"
                         @click="checkPics">使用素材</el-button>
              <span v-if="permissions.material_manage">
                <el-upload class="upload-demo"
                           accept="image/*,video/*"
                           :action="materialAction"
                           :data="{'treeId':currentTreeId}"
                           :on-success="handleUploadSuccess"
                           :on-error="handleUploadError"
                           :before-upload="beforeUpload"
                           :headers="headers"
                           :show-file-list="false">
                  <el-button class="mr10"
                             icon="el-icon-upload2"
                             type="primary">本地素材</el-button>
                </el-upload>
                <el-button class="mr10"
                           icon="el-icon-upload2"
                           type="primary"
                           @click.stop="openUploadNetDialog">网络素材</el-button>
                <el-button class="mr10"
                           type="danger"
                           icon="el-icon-delete"
                           @click.stop="delMaterial()">删除素材</el-button>
                <el-select v-model="sleOptions.name"
                           placeholder="素材移动至"
                           class="mb20"
                           style="width:180px;"
                           size="small">
                  <template slot="prefix">
                    <div class="el-select-prefix__div">
                      <i class="el-icon-sort" />
                    </div>
                  </template>
                  <el-option :label="sleOptions.name"
                             :value="sleOptions.id">
                    <el-tree ref="tree2"
                             :data="treeData"
                             :filter-node-method="filterNode"
                             :props="defaultProps"
                             highlight-current
                             @node-click="handleSelClick" />
                  </el-option>
                </el-select>
              </span>
              <div class="abs_video">
                <el-radio-group v-model="checkMaterialType"
                                @change="radioChange"
                                size="small">
                  <el-radio-button label="image">图片</el-radio-button>
                  <el-radio-button label="video">视频</el-radio-button>
                </el-radio-group>
              </div>
            </div>
            <div class="pictrueList acea-row"
                 v-loading="loadingPic">
              <div v-show="materials.length == 0 "
                   class="imagesNo">
                <i class="el-icon-picture"
                   style="font-size: 60px; color: rgb(219, 219, 219)" />
                <span class="imagesNo_sp">素材库为空</span>
              </div>
              <div class="conters scrollbarAll">
                <div v-for="(item, index) in materials"
                     :key="index"
                     class="gridPic">
                  <span class="num_badge"
                        v-if="item.num > 0">{{item.num}}</span>
                  <img style="object-fit: contain;"
                       :src="item.url ? item.url : localImg"
                       :class="item.isSelect ? 'on' : ''"
                       @click="changImage(item, index, materials)"
                       v-if="item.bigType == 'image'" />
                  <video :src="item.url"
                         :class="item.isSelect ? 'on' : ''"
                         @click="changImage(item, index, materials)"
                         v-if="item.bigType == 'video'" />
                </div>
              </div>
            </div>
          </div>
          <div class="block">
            <el-pagination :page-sizes="[6, 12, 18]"
                           :page-size="page.pageSize"
                           :current-page="page.currentPage"
                           :pager-count="5"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="page.total"
                           @size-change="handleSizeChange"
                           @current-change="pageChange" />
          </div>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog :title="bizTitle"
               :visible.sync="visible"
               width="400px"
               destroy-on-close
               append-to-body
               :close-on-click-modal="false"
               :modal="false"
               @close="closeModel">
      <el-form ref="editPram"
               :model="editPram"
               label-width="100px"
               v-loading="loading">
        <el-form-item label="上级分类"
                      prop="parentId"
                      :rules="[{type: 'number',required: true,message: '请选择上级分类',trigger: ['blur', 'change']}]">
          <el-select v-model="sleOptions.name"
                     placeholder="选择上级分类"
                     style="width:260px;"
                     size="small">
            <el-option :label="sleOptions.name"
                       :value="sleOptions.id">
              <el-tree ref="tree3"
                       :data="treeData"
                       :filter-node-method="filterNode"
                       :props="defaultProps"
                       highlight-current
                       @node-click="handleClick" />
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称"
                      prop="name"
                      :rules="[{required: true, message: '请输入分类名称',trigger: ['blur', 'change']}]">
          <el-input v-model="editPram.name"
                    placeholder="分类名称" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="editPram.sort"
                           style="width:260px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="handlerSubmit('editPram')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="上传网络附件"
               :visible.sync="uploadNetDialogVisible"
               :close-on-click-modal="false"
               width="600px"
               destroy-on-close
               append-to-body
               :modal="false">
      <el-form ref="netForm"
               label-width="100px"
               :rules="netFormRules"
               :model="netForm">
        <el-form-item label="网络地址"
                      prop="netUrl">
          <el-input placeholder="请输入网络地址"
                    v-model="netForm.netUrl" />
        </el-form-item>
        <el-form-item label="附件名称"
                      prop="fileName">
          <el-input placeholder="请输入附件名称不带扩展名"
                    v-model="netForm.fileName" />
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="uploadNetDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="uploadNetFile">上传</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import store from "@/store";
import { mapGetters } from 'vuex'
import { fetchTree, addObj, getObj, delObj, putObj } from "@/api/admin/sys-tree"
import { fetchList, moveMaterialFile, uploadNet, delObj as delFile } from "@/api/admin/sys-file"

export default {
  name: "UploadMaterial",
  props: {
    materialType: {
      type: String
    },
    isMore: {
      type: Number,
      default: 1,
    },
  },
  computed: {
    ...mapGetters(['permissions'])//权限列表
  },
  data () {
    return {
      uploadNetDialogVisible: false,
      netForm: {
        netUrl: undefined,
        fileName: undefined,
        bucketName: 'MATERIAL'
      },
      netFormRules: {
        netUrl: [{ required: true, message: '请输网络地址', trigger: "blur" }]
      },
      dialogLoading: undefined,
      loading: false,
      loadingPic: false,
      materialVisible: true,
      visible: false,
      materialAction: store.getters.materialAction,
      headers: {
        Authorization: "Bearer " + store.getters.access_token,
      },
      filterText: "",
      treeData: [],
      sleOptions: {
        name: "全部素材",
        id: 0,
      },
      defaultProps: {
        label: "name",
      },
      editPram: {
        treeId: undefined,
        name: undefined,
        parentId: undefined,
        treeType: 2,
        sort: 1
      },
      bizTitle: "",
      currentTreeId: 0,
      page: {
        total: 0,
        currentPage: 1,
        pageSize: 12
      },
      materials: [],
      checkMaterials: [],
      checkMaterialType: 'image'
    };
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val);
    },
  },
  created () {
    if (!!this.materialType) {
      this.checkMaterialType = this.materialType
    }
  },
  mounted () {
    this.getList();
    this.getFileList();
  },
  methods: {
    // 上传网络附件
    uploadNetFile () {
      this.$refs.netForm.validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '下载网络附件到本系统中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          uploadNet(this.netForm).then(resp => {
            loading.close()
            this.uploadNetDialogVisible = false
            this.getFileList();
            this.$message.success(resp.data.message);
          }).catch(message => {
            loading.close()
          })
        }
      })
    },
    // 上传网络附件弹框
    openUploadNetDialog () {
      this.uploadNetDialogVisible = true
      this.netForm = {
        netUrl: undefined,
        fileName: undefined,
        bucketName: 'MATERIAL'
      }
    },
    // 文件上传前后调
    beforeUpload (file) {
      return new Promise((resolve, reject) => {
        if (!["image", "video"].includes(file.type.split("/")[0])) {
          this.$message.warning("只允许上传视频或图片")
          return reject(false)
        }
        this.dialogLoading = this.$loading({
          lock: true,
          text: "上传中，请稍候...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        return resolve(true);
      });
    },
    // 关不dialog
    handleClose (done) {
      this.materialCallBack()
      done()
    },
    closeModel () {
      this.$refs["editPram"].resetFields();
    },
    // 搜索分类
    filterNode (value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 所有分类
    getList () {
      fetchTree({ treeType: 2 }).then((res) => {
        this.treeData = res.data.data || [];
        this.treeData.unshift({ id: 0, name: "全部素材" });
      });
    },
    // 添加分类
    onAdd (node) {
      this.bizTitle = "添加分类";
      this.sleOptions = { ...node }
      this.editPram = {
        treeId: undefined,
        name: undefined,
        parentId: node.id,
        treeType: 2,
        sort: 1
      };
      this.visible = true;
    },
    // 编辑分类
    onEdit (id) {
      this.bizTitle = "编辑分类";
      this.loading = true;
      getObj(id).then((res) => {
        let data = res.data.data;
        this.editPram = data;
        this.sleOptions = { id: data.parentId, name: data.parentId == 0 ? '全部素材' : data.parentName }
        this.loading = false;
        this.visible = true;
      });
    },
    // 提交分类表单
    handlerSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.bizTitle === "添加分类"
            ? addObj(this.editPram).then((resp) => {
              this.$message.success(resp.data.message);
              this.visible = false;
              this.getList();
            })
            : putObj(this.editPram).then((resp) => {
              this.$message.success(resp.data.message);
              this.visible = false;
              this.getList();
            });
        }
      });
    },
    // 删除分类
    handleDelete (id) {
      delObj(id).then((resp) => {
        this.$message.success(resp.data.message);
        this.getList();
      });
    },
    // 点击分类
    handleNodeClick (data) {
      this.currentTreeId = data.id;
      this.sleOptions = { ...data }
      this.getFileList();
    },
    // 文件列表
    getFileList () {
      this.loadingPic = true;
      this.checkMaterials = [];
      let params = {
        current: this.page.currentPage,
        size: this.page.pageSize,
        descs: 'create_time',
        classification: 'material',
        bigType: this.checkMaterialType,
        treeId: this.currentTreeId == 0 ? undefined : this.currentTreeId
      }
      fetchList(params).then(resp => {
        this.materials = resp.data.data.records
        this.page.total = resp.data.data.total
        this.loadingPic = false;
      })
    },
    // 改变当前页数
    pageChange (page) {
      this.page.currentPage = page;
      this.getFileList();
    },
    // 改变每页条数
    handleSizeChange (size) {
      this.page.pageSize = size;
      this.getFileList();
    },
    // 选中图片
    changImage (item, index, row) {
      let activeIndex = 0;
      if (!item.isSelect) {
        this.$set(item, "isSelect", true);
        this.checkMaterials.push(item);
      }
      else {
        this.$set(item, "isSelect", !item.isSelect);
        this.checkMaterials.map((el, index) => {
          if (el.id == item.id) {
            activeIndex = index;
          }
        });
        this.checkMaterials.splice(activeIndex, 1);
      }
      this.materials.map((el, i) => {
        if (el.isSelect) {
          this.checkMaterials.filter((el2, j) => {
            if (el.id == el2.id) {
              this.$set(el, "num", j + 1)
            }
          });
        } else {
          this.$set(el, "num", 0)
        }
      });
    },
    materialCallBack (obj) {
      this.$emit("materialCallBack", obj)
    },
    // 点击使用选中图片
    checkPics () {
      if (this.checkMaterials.length < 1) {
        return this.$message.warning("请先选择素材");
      }
      let callbackMaterials = this.checkMaterials.filter(item => {
        if (!this.materialType) return true
        return item.bigType == this.materialType
      })
      if (callbackMaterials.length > this.isMore) {
        return this.$message.warning(`最多只能选择${this.isMore}个素材`);
      }
      if (callbackMaterials.length == 0) {
        return this.$message.warning(`只能选择${this.materialType}类型素材`);
      }
      this.materialCallBack([...callbackMaterials])
    },
    // 删除图片
    delMaterial () {
      if (this.checkMaterials.length != 1)
        return this.$message.warning("请先选择一个素材");
      delFile(this.checkMaterials[0].id).then(resp => {
        this.$message.success("删除素材成功")
        this.getFileList()
      })
    },
    // 选择上级分类
    handleClick (node) {
      this.sleOptions = { ...node }
      this.editPram.parentId = node.id
    },
    // 移动分类点击
    handleSelClick (node) {
      this.sleOptions = { ...node }
      let checkMaterialIds = this.checkMaterials.map(item => item.id)
      if (checkMaterialIds.length > 0) {
        if (node.id == 0) return this.$message.warning("不能移动至全部素材")
        let params = {
          treeId: node.id,
          fileIds: checkMaterialIds.join(",")
        }
        moveMaterialFile(params).then(resp => {
          this.$message.success(resp.data.message)
          this.getFileList()
        })
      } else {
        this.$message.warning("请先选择需要移动的素材");
      }
    },
    // 切换类型
    radioChange () {
      this.page = {
        total: 0,
        currentPage: 1,
        pageSize: 12
      }
      this.getFileList();
    },
    // 上传成功处理
    handleUploadSuccess () {
      if (this.dialogLoading) {
        this.dialogLoading.close()
        this.dialogLoading = undefined;
      }
      this.$message.success("上传成功")
      this.getFileList()
    },
    // 上传失败
    handleUploadError () {
      if (this.dialogLoading) {
        this.dialogLoading.close()
        this.dialogLoading = undefined;
      }
      this.$message.success("上传失败")
    }
  },
};
</script>

<style scoped lang="scss">
.el-select-prefix__div {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.demo::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}

.demo {
  scrollbar-width: none; /* firefox */
  -ms-overflow-style: none; /* IE 10+ */
  overflow-x: hidden;
  overflow-y: auto;
}
.temp {
  height: 0;
  margin-bottom: 0;
  border: none;
  padding: 0;
}
.selectTreeClass {
  background: #d5e8fc;
}
.treeBox {
  width: 100%;
  height: 100%;
}
.upload-demo {
  display: inline-block !important;
  float: left;
}
.tree_w {
  padding: 20px 30px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  padding-right: 8px;
  color: #4386c6;
}
.custom-tree-node-label {
  display: block;
  width: 125px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.el-ic {
  display: none;
  i,
  span {
    /*padding: 0 14px;*/
    font-size: 18px;
    font-weight: 600;
  }
  .svg-icon {
    color: #4386c6;
  }
}
.el-tree-node__content {
  height: 38px;
}
.el-tree-node__expand-icon {
  color: #428bca;
  /*padding: 10px 10px 0px 10px !important;*/
}
.el-tree-node__content:hover .el-ic {
  color: #428bca !important;
  display: inline-block;
}
.el-tree-node__content:hover {
  font-weight: bold;
}
.el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content
  :hover {
  .el-tree-node__expand-icon.is-leaf {
    color: transparent;
    cursor: default;
  }
  /*background-color: #3998d9;*/
  .custom-tree-node {
    font-weight: bold;
  }
  .el-tree-node__expand-icon {
    font-weight: bold;
  }
}
.el-dialog__body {
  .upload-container .image-preview .image-preview-wrapper img {
    height: 100px;
  }
  .el-dialog .el-collapse-item__wrap {
    padding-top: 0px;
  }
  .spatial_img {
    .el-collapse-item__wrap {
      margin-bottom: 0;
      padding-top: 0px;
    }
  }
  .upload-container .image-preview .image-preview-wrapper {
    width: 120px;
  }
  .upload-container .image-preview .image-preview-action {
    line-height: 100px;
    height: 100px;
  }
}
.trees-coadd {
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  .scollhide {
    overflow-x: hidden;
    overflow-y: scroll;
    padding: 10px 0 10px 0;
    box-sizing: border-box;
    .trees {
      width: 100%;
    }
  }
  .scollhide::-webkit-scrollbar {
    display: none;
  }
}
.conters {
  display: flex;
  flex-wrap: wrap;
  /*max-height: 296px;*/
  overflow: auto;
}
.conters:after {
  content: "";
  width: 410px !important;
}
.gridPic {
  margin-right: 15px;
  margin-bottom: 10px;
  width: 110px;
  height: 110px;
  position: relative;
  cursor: pointer;
  img {
    width: 100%;
    height: 100%;
    display: block;
  }
  video {
    width: 100%;
    height: 100%;
    display: block;
  }
  .num_badge {
    position: absolute;
    bottom: 6px;
    right: 6px;
    display: inline-block;
    min-width: 20px;
    height: 20px;
    border-radius: 10px;
    background: #1890ff;
    font-size: 14px;
    text-align: center;
    color: #fff;
    line-height: 20px;
  }
}
.conter {
  width: 99%;
  height: 100%;
  .bnt {
    width: 100%;
    padding: 0 13px 10px 7px;
    box-sizing: border-box;
    display: flex;
  }
  .pictrueList {
    /*padding-left: 15px;*/
    width: 100%;
    el-image {
      width: 100%;
      border: 2px solid #fff;
    }
    .on {
      border: 2px solid #1890ff;
    }
  }
  .el-image {
    width: 110px;
    height: 110px;
    cursor: pointer;
  }
  .imagesNo {
    width: 100%;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    margin: 65px 0;
    .imagesNo_sp {
      font-size: 13px;
      color: #dbdbdb;
      line-height: 3;
    }
  }
}
.relative {
  position: relative;
}
.abs_video {
  position: absolute;
  right: 20px;
  top: 0;
}
</style>
